package com.zhuhao.utils.jasypt;

import org.jasypt.util.digest.Digester;
import org.jasypt.util.password.BasicPasswordEncryptor;
import org.jasypt.util.password.ConfigurablePasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 加密工具测试
 *
 * @Author haozhu7
 * @Date 2023/3/8 18:02
 **/
public class JasyptUtil {

    /**
     * 一般摘要加密（org.jasypt.util.digest.*）
     */
    @Test
    public void digesterTest(){
        Digester digester = new Digester();
        digester.setAlgorithm("SHA-1");
        byte[] digest = digester.digest("1234".getBytes(StandardCharsets.UTF_8));
        System.out.println(digest);

    }

    /**
     * 可用于在用户注册时加密密码并在用户登录时检查输入密码。
     */
    @Test
    public void encryptorPasswordTest() {
        BasicPasswordEncryptor basicPasswordEncryptor = new BasicPasswordEncryptor();
        String encryptPassword = basicPasswordEncryptor.encryptPassword("1234");
        //每次加密后生成的密码都不一样，用checkPassword检查时都为true
        System.out.println(encryptPassword);

        boolean b = new BasicPasswordEncryptor().checkPassword("1234", encryptPassword);
        boolean f = new BasicPasswordEncryptor().checkPassword("1234", "Bd/vVPiRi6PmwXLdXQJ6gdnoBEPahDyd");
        System.out.println(b);
        System.out.println(f);
    }

    /**
     * 更强壮，也更耗时
     * 可用于在用户注册时加密密码并在用户登录时检查输入密码。
     */
    @Test
    public void strongEncryptorPasswordTest() {
        StrongPasswordEncryptor strongPasswordEncryptor = new StrongPasswordEncryptor();
        String encryptPassword = strongPasswordEncryptor.encryptPassword("1234");
        //每次加密后生成的密码都不一样，用checkPassword检查时都为true
        System.out.println(encryptPassword);

        boolean b = new StrongPasswordEncryptor().checkPassword("1234", encryptPassword);
        boolean f = new StrongPasswordEncryptor().checkPassword("1234", "HflQYwU6QGDDQUjyh55ce4id9pXmOPE6cJEHMkGNAve6/XxCoaqtidR4Q5lgSw0p");
        System.out.println(b);
        System.out.println(f);
    }

    /**
     * 可以配置算法的加密
     */
    @Test
    public void configurableEncryptorPasswordTest() {
        ConfigurablePasswordEncryptor configurablePasswordEncryptor = new ConfigurablePasswordEncryptor();
        configurablePasswordEncryptor.setAlgorithm("SHA-1");
        configurablePasswordEncryptor.setPlainDigest(true);

        String encryptPassword = configurablePasswordEncryptor.encryptPassword("1234");
        System.out.println(encryptPassword);

        boolean b = configurablePasswordEncryptor.checkPassword("1234", encryptPassword);
        System.out.println(b);
        boolean f = configurablePasswordEncryptor.checkPassword("1234", "cRDtpNCeBiql5KOQsKVyrA0sAiA=");
        System.out.println(f);
    }

}
